<?php

namespace App\Http\Controllers;

use App\Http\ApiConfig;
use App\Http\Services\ApiLogService;
use Laravel\Lumen\Routing\Controller;
use Illuminate\Http\Request;
use App\Models\Request\ReqParam;
use App\Models\Request\ResData;

class ApiController extends Controller
{
    public function index(Request $request)
    {
        // create request head
        $reqParam = new ReqParam($request->input());
        $reqParamHead = $reqParam->head;
        // save api log
        $apiLogService = new ApiLogService();
        $apiLogService->create($request);

        // run bizfunc
        $result = $this->funcRun($reqParam);
        $resdat = new ResData($reqParamHead, $result);
        return $this->suc($resdat);
    }

    private function funcRun($params)
    {
        $func = ApiConfig::$config[$params->head->bizcode][$params->head->funcode];

        // 运行业务方法
        $refClass = new \ReflectionClass($func['class']);
        $refMethod = $refClass->getMethod($func['method']);
        $instance = $refClass->newInstance();
        return $refMethod->invoke($instance, $params);
    }

    /**
     * 成功返回.
     *
     * @param array $data
     * @param string $bizcode
     */
    public function suc($data = [])
    {
        $this->parseNull($data);
        $result = $this->createRes("SUC000", "成功", $data);
        if (env('APP_ENV') == 'product') {
            return base64_encode(openssl_encrypt(json_encode($result), "AES-128-CBC", env('AES_KEY'), OPENSSL_RAW_DATA, env('AES_IV')));
        }
        return $result;
    }

    /**
     * 失败返回.
     *
     * @param string $code
     * @param array $data
     * @param string $msg
     *
     * @return mixed
     */
    public function err($code = "ERR001", $data = [], $msg = "失败")
    {
        return $this->createRes($code, $msg, $data);
    }

    /**
     * @param $filePath
     */
    public function download($filePath)
    {
        header('Content-Encoding: UTF-8');
        header("Content-type:application/octet-stream");
        header("Content-Disposition:attachment;filename=" . basename($filePath));
        header("Accept-ranges:bytes");
        readfile($filePath); //读取文件
        unlink($filePath);
        exit;
    }

    private function createRes($rescode, $resmsg, $resdat)
    {
        return response([
            "rescode" => $rescode,
            "resmsg" => $resmsg,
            "restim" => date("Ymdhis"),
            "resdat" => $resdat
        ]);
    }

    /**
     * 如果返回的数据中有 null 则那其值修改为空 （安卓和IOS 对null型的数据不友好，会报错）.
     *
     * @param $data
     */
    private function parseNull(&$data)
    {
        if (is_array($data)) {
            foreach ($data as &$v) {
                $this->parseNull($v);
            }
        } else {
            if (null === $data) {
                $data = "";
            }
        }
    }
}
